<?php declare(strict_types=1);


namespace App\Api\V2\Controller\Incoming;


use App\Api\Controllers\BaseController;
use App\Api\Controllers\Basequery\StorePayWaysController;
use App\Models\AlipayAppOauthUsers;
use App\Models\ExtensionWorkers;
use App\Models\ExtensionWorkerStores;
use App\Models\IncomingQrs;
use App\Models\Merchant;
use App\Models\MerchantStore;
use App\Models\ProvinceCity;
use App\Models\Store;
use App\Models\StoreBank;
use App\Models\StoreImg;
use App\Models\User;
use App\Models\VbillStore;
use App\Services\Incoming\IncomingService;
use App\Traits\ResponseTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\JWTAuth;

class IncomingController extends BaseController
{
    use ResponseTrait;

    //进件详情
    public function storeStatus(Request $request): string
    {
        try {
            $user = $this->parseToken();
            $worker = ExtensionWorkers::query()->where([
                "phone" => $user->worker_phone
            ])->first();

            if (empty($worker)) {
                throw new \Exception("推广人员不存在");
            }
            $store_id = $user->store_id;
            $store = Store::query()->where("store_id", $store_id)->first();
            $status = 0;
            $status_desc = "店铺不存在";
            if (!empty($store)) {
                $status = $store->status;
                $status_desc = $store->status_desc;
            }
            $extension_worker_merchant = DB::table("extension_worker_merchant")->where([
                "worker_id" => $worker->id,
                "phone" => $user->phone,
            ])->first();
            return $this->successResponse("ok", [
                "data" => [
                    "status" => $status,
                    "status_desc" => $status_desc,
                    "store" => $store,
                    "is_change" => $extension_worker_merchant->is_change
                ]
            ]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    //进件  none-auth
    public function incoming(Request $request): string
    {
        try {
            $user = $this->parseToken();


            $service = new IncomingService();
            $data = $request->all();
            $data["store_id"] = $user->store_id;
            if (!empty($user->wid) && $user->wid == 1) {
                $data["user_id"] = 901;
            } else {
                $data["user_id"] = $user->user_id;
            }
            $data["people_phone"] = $user->phone;


            $worker = ExtensionWorkers::query()->where([
                "status" => 1,
                "phone" => $user->worker_phone
            ])->first();

            if (empty($worker)) {
                throw new \Exception("推广人员不存在");
            }


            $data = $service->validator($data);
            $user = User::query()->where("id", $data["user_id"])->first();
            if (empty($user)) {
                throw new \Exception("用户不存在");
            }


            $stores = [
                'config_id' => $user->config_id,
                'user_id' => $user->id,
                'merchant_id' => '',
                'store_id' => $data["store_id"],
                'store_name' => $data["store_name"],
//                'store_type' => $store_type,
                'store_type_name' => $data["store_type_name"] ?? "",
                'store_email' => $data["store_email"] ?? "",
                'store_short_name' => $data["store_short_name"] ?? "",
                'people' => $data["people"] ?? "", //负责人
                'people_phone' => $data["people_phone"] ?? "",
                'province_code' => $data["province_code"] ?? "",
                'city_code' => $data["city_code"] ?? "",
                'area_code' => $data["area_code"] ?? "",
                'store_address' => $data["store_address"] ?? "",
                'head_name' => $data["head_name"] ?? "", //法人
                'head_sfz_no' => $data["head_sfz_no"] ?? "",
                'head_sfz_time' => $data["head_sfz_time"] ?? "",
                'head_sfz_stime' => $data["head_sfz_stime"] ?? "",
                'category_id' => $data["category_id"] ?? "",
                'category_name' => $data["category_name"] ?? "",
                'store_license_no' => $data["store_license_no"] ?? "",
                'store_license_time' => $data["store_license_time"] ?? "",
                'store_license_stime' => $data["store_license_stime"] ?? "",
                'weixin_name' => $data["weixin_name"] ?? "",
                'weixin_no' => $data["weixin_no"] ?? "",
                'alipay_name' => $data["alipay_name"] ?? "",
                'alipay_account' => $data["alipay_account"] ?? "",
                'dlb_micro_biz_type' => $data["dlb_micro_biz_type"] ?? "", //哆啦宝-经营类型
                'dlb_industry' => $data["dlb_industry"] ?? "", //哆啦宝店铺一级行业
                'dlb_second_industry' => $data["dlb_second_industry"] ?? "", //店铺二级行业
                'dlb_province' => $data["dlb_province"] ?? "", //哆啦宝-商户省份
                'dlb_city' => $data["dlb_city"] ?? "", //哆啦宝商户城市
                'dlb_bank' => $data["dlb_bank"] ?? "", //哆啦宝-银行名称
                'dlb_sub_bank' => $data["dlb_sub_bank"] ?? "", //哆啦宝-银行分行名称
                'dlb_pay_bank_list' => $data["dlb_pay_bank_list"] ?? "", //支付类型+费率
                "hkrt_bus_scope_code" => $data["hkrt_bus_scope_code"] ?? "",
                "store_type" => $data["store_type"] ?? "",
                "province_name" => "",
                "city_name" => "",
                "area_name" => "",
                "lng" => $data["longitude"] ?? 0,
                "lat" => $data["latitude"] ?? 0,
                "is_incoming" => empty($data["is_incoming"]) ? 1 : $data["is_incoming"],
            ];

            //图片信息
            $store_imgs = [
                'store_id' => $data["store_id"] ?? "",
                'head_sfz_img_a' => $data["head_sfz_img_a"] ?? "",
                'head_sfz_img_b' => $data["head_sfz_img_b"] ?? "",
                'store_license_img' => $data["store_license_img"] ?? "",
                'store_industrylicense_img' => $data["store_industrylicense_img"] ?? "",
                'store_logo_img' => $data["store_logo_img"] ?? "",
                'store_img_a' => $data["store_img_a"] ?? "",
                'store_img_b' => $data["store_img_b"] ?? "",
                'store_img_c' => $data["store_img_c"] ?? "",
                'bank_img_a' => $data["bank_img_a"] ?? "",
                'bank_img_b' => $data["bank_img_b"] ?? "",
                'store_other_img_a' => $data["store_other_img_a"] ?? "",
                'store_other_img_b' => $data["store_other_img_b"] ?? "",
                'store_other_img_c' => $data["store_other_img_c"] ?? "",
                'head_sc_img' => $data["head_sc_img"] ?? "",
                'head_store_img' => $data["head_store_img"] ?? "",
                'bank_sfz_img_a' => $data["bank_sfz_img_a"] ?? "",
                'bank_sfz_img_b' => $data["bank_sfz_img_b"] ?? "",
                'bank_sc_img' => $data["bank_sc_img"] ?? "",
                'store_auth_bank_img' => $data["store_auth_bank_img"] ?? "",
                "dlb_settler_hold_settlecard" => $data["dlb_settler_hold_settlecard"] ?? ""
            ];


            //银行卡信息
            $store_banks = [
                'store_id' => $data["store_id"] ?? "",
                'store_bank_no' => $data["store_bank_no"] ?? "",
                'store_bank_name' => $data["store_bank_name"] ?? "",
                'store_bank_phone' => $data["store_bank_phone"] ?? "",
                'store_bank_type' => $data["store_bank_type"] ?? "",
                'bank_name' => $data["bank_name"] ?? "",
                'bank_no' => $data["bank_no"] ?? "",
                'sub_bank_name' => $data["sub_bank_name"] ?? "",
                'bank_province_code' => $data["bank_province_code"] ?? "",
                'bank_city_code' => $data["bank_city_code"] ?? "",
                'bank_area_code' => $data["bank_area_code"] ?? "",
                'bank_sfz_no' => $data["bank_sfz_no"] ?? "",//持卡人默认是法人
                'bank_sfz_time' => $data["bank_sfz_time"] ?? "",
                'bank_sfz_stime' => $data["bank_sfz_stime"] ?? "",
                "reserved_mobile" => $data["reserved_mobile"] ?? "" //海科融通结算卡预留手机号
            ];


            $store = Store::query()->where('store_id', $data["store_id"])->first();
            $store_bank = StoreBank::where('store_id', $data["store_id"])->first();
            $store_img = StoreImg::where('store_id', $data["store_id"])->first();

            if (!empty($store)) {
                $is_store = 1;
            } else {
                $is_store = 0;
            }

            $is_merchant = 0;
            //判断手机号是否被注册
            if (!empty($data["people_phone"])) {
                $people_phone = $data["people_phone"];
                //验证手机号
                if (!preg_match("/^1[3456789]{1}\d{9}$/", $people_phone)) {
                    return $this->errorResponse("手机号码格式不正确");
                }
                $merchant = Merchant::where('phone', $people_phone)
                    ->select('id')->first();
                if (!empty($merchant)) {
                    $is_merchant = 1;
                }
                if ($is_merchant == 1 && $is_store == 0) {
                    return $this->errorResponse("手机号已被注册,请更换");
                }
            }
            //开启事务
            try {
                DB::beginTransaction();
                //入库账户
                if (!empty($data["people_phone"])) {
                    //未注册
                    if ($is_merchant == 0) {
                        //注册账户
                        $dataIN = [
                            'pid' => 0,
                            'type' => 1,
                            'name' => $data["people"] ?? "",
                            'email' => '',
                            'password' => bcrypt('000000'),
                            'pay_password' => bcrypt('000000'),
                            'phone' => $data["people_phone"] ?? "",
                            'user_id' => $user->id,
                            'config_id' => $user->config_id,
                            'wx_openid' => ''
                        ];
                        $merchant = Merchant::query()->create($dataIN);
                        $merchant_id = $merchant->id;
                        $stores['merchant_id'] = $merchant_id;
                        MerchantStore::create([
                            'store_id' => $data["store_id"],
                            'merchant_id' => $merchant_id
                        ]);
                    }
                }

                if (!empty($store)) {
                    //修改   不修改归属ID
                    $stores['user_id'] = $store->user_id;
                    $stores['config_id'] = $store->config_id;
                    $stores = array_filter($stores, function ($v) {
                        if ($v == "") {
                            return false;
                        } else {
                            return true;
                        }
                    });
                    $store->update($stores);
                    $store->save();
                } else {
                    $rules = [
                        'store_name' => 'unique:stores',
                    ];
                    $validator = Validator::make($data, $rules);
                    if ($validator->fails()) {
                        return $this->errorResponse("门店名称在系统中已经存在");
                    }
                    $store = Store::query()->create($stores);
                }

                if ($store_img) {
                    $store_img->update(array_filter($store_imgs));
                    $store_img->save();
                } else {
                    StoreImg::query()->create($store_imgs);
                }
                if ($store_bank) {
                    $store_bank->update(array_filter($store_banks));
                    $store_bank->save();
                } else {
                    $stores['store_type'] = 1;
                    $stores['store_type_name'] = '个体';
                    StoreBank::query()->create($store_banks);
                }
                //在这里讲店铺ID保存
                ExtensionWorkerStores::query()->firstOrCreate([
                    "worker_id" => $worker->id,
                    "store_id" => $data['store_id'],
                    "phone" => $data["people_phone"]
                ]);
                VbillStore::query()->firstOrCreate([
                    'store_id' => $store->store_id,
                    "config_id" => $store->config_id
                ]);
                //配置通道
                $service->configure_channel($data["store_id"]);
                DB::commit();
                //提交进件
                $return = $service->base_open_ways($store, "", "");
            } catch (\Exception $ex) {
                Log::info($ex->getMessage() . ' | ' . $ex->getFile() . ' | ' . $ex->getLine());
                DB::rollBack();
                return $this->errorResponse($ex->getMessage());
            }
            return $this->successResponse("资料添加成功", [
                'store_id' => $data["store_id"],
                'status' => $return["status"],
                'message' => $return["message"],
            ]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    //查询进件状态并且bind-商户号
    public function searchIncomingResults(Request $request): string
    {
        try {
            $user = $this->parseToken();
            $worker = ExtensionWorkers::query()->where([
                "phone" => $user->worker_phone
            ])->first();

            if (empty($worker)) {
                throw new \Exception("推广人员不存在");
            }

            $store_id = $user->store_id;

            $ch = Db::table('store_pay_ways')->where(['store_id' => $store_id, 'status' => 1])->first();
            if (!empty($ch)) {
                return $this->successResponse("ok", ["data" => ["status" => 1, "status_text" => "入驻审核通过", "msg" => "入驻审核通过"]]);
            }

            $service = new IncomingService();

            list($status, $status_txt, $msg, $data) = $service->check_results(["store_id" => $store_id]);
            if ($status == 2) {

                return $this->successResponse("ok", ["data" => [
                    "status" => $status,
                    "status_text" => $status_txt,
                    "msg" => $msg
                ]]);
            } else if ($status == 1) {
                //bind 商户号 ， 更新店铺状态
                $service->setMno($store_id);
            }
            return $this->successResponse("ok", ["data" => [
                "status" => $status,
                "status_text" => $status_txt,
                "msg" => $msg
            ]]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


    //查看店铺详细信息
    public function storeInfo(Request $request): string
    {
        $user = $this->parseToken();
        $worker = ExtensionWorkers::query()->where([
            "phone" => $user->worker_phone
        ])->first();
        if (empty($worker)) {
            throw new \Exception("推广人员不存在");
        }
        $store_id = $user->store_id;
        //查看店铺信息
        $store = Store::query()->where('store_id', $store_id)->first();
        $store_bank = StoreBank::where('store_id', $store_id)->first();
        $store_img = StoreImg::where('store_id', $store_id)->first();
        $data = [
            "store" => $store->toArray(),
            "store_bank" => $store_bank->toArray(),
            "store_img" => $store_img->toArray()
        ];


        $store_alipay_account = '';
        $AlipayAppOauthUsers = AlipayAppOauthUsers::query()->where('store_id', $store_id)->first();
        if ($AlipayAppOauthUsers) {
            $store_alipay_account = $AlipayAppOauthUsers->alipay_user_account;
        }

        if ($store->category_id >= 416) {
            $category = DB::table('vbill_store_category')->where('mcc', $store->category_id)->first();
            $store->category_id = $category->id;
            $store->category_name = $category->category_name;
        }

        $type = $request->get('type');
        if ($type == "") {
            $type = 'head_info,store_info,account_info,license_info';
        }
        $type_array = explode(",", $type);
        $data_r = [];
        $storeController = new \App\Api\Controllers\User\StoreController();
        foreach ($type_array as $k => $v) {
            if ($v == 'head_info') {
                $data = [
                    'head_name' => $store->head_name,//法人
                    'head_sfz_no' => $store->head_sfz_no,
                    'head_sfz_img_a' => $store_img->head_sfz_img_a,
                    'head_sfz_img_b' => $store_img->head_sfz_img_b,
                    'people' => $store->people,
                    'people_phone' => $store->people_phone,
                    'head_sfz_time' => $store->head_sfz_time,
                    'head_sfz_stime' => $store->head_sfz_stime,
                ];

                $data_r[$v] = $data;
            }

            if ($v == 'store_info') {
                $data = [
                    'people' => $store->people,
                    'people_phone' => $store->people_phone,
                    'store_email' => $store->store_email,
                    'store_name' => $store->store_name,
                    'store_short_name' => $store->store_short_name,
                    'province_code' => $store->province_code,
                    'city_code' => $store->city_code,
                    'area_code' => $store->area_code,
                    'province_name' => $store->province_name,
                    'city_name' => $store->city_name,
                    'area_name' => $store->area_name,
                    'store_address' => $store->store_address,
                    'store_type' => $store->store_type,
                    'store_type_name' => $store->store_type_name,
                    'category_id' => $store->category_id,
                    'category_name' => $store->category_name,
                    'store_logo_img' => $store_img->store_logo_img,
                    'store_img_a' => $store_img->store_img_a,
                    'store_img_b' => $store_img->store_img_b,
                    'store_img_c' => $store_img->store_img_c,
                    'status' => $store->status,
                    'status_desc' => $store->status_desc,
                    'alipay_name' => $store->alipay_name,
                    'alipay_account' => $store->alipay_account,

                ];
                $data_r[$v] = $data;
            }

            if ($v == 'account_info') {
                $data = [
                    'store_alipay_account' => $store_alipay_account,
                    'store_bank_no' => $store_bank->store_bank_no,
                    'store_bank_phone' => $store_bank->store_bank_phone,
                    'store_bank_name' => $store_bank->store_bank_name,
                    'store_bank_type' => $store_bank->store_bank_type,
                    'bank_name' => $store_bank->bank_name,
                    'bank_no' => $store_bank->bank_no,
                    'sub_bank_name' => $store_bank->sub_bank_name,
                    'bank_province_code' => $store_bank->bank_province_code,
                    'bank_city_code' => $store_bank->bank_city_code,
                    'bank_area_code' => $store_bank->bank_area_code,
                    'bank_province_name' => $storeController->city_name($store_bank->bank_province_code),
                    'bank_city_name' => $storeController->city_name($store_bank->bank_city_code),
                    'bank_area_name' => $storeController->city_name($store_bank->bank_area_code),
                    'bank_img_a' => $store_img->bank_img_a,
                    'bank_img_b' => $store_img->bank_img_b,
                    'bank_sfz_img_a' => $store_img->bank_sfz_img_a,
                    'bank_sfz_img_b' => $store_img->bank_sfz_img_b,
                    'bank_sc_img' => $store_img->bank_sc_img,
                    'store_auth_bank_img' => $store_img->store_auth_bank_img,
                    'bank_sfz_time' => $store_bank->bank_sfz_time,
                    'bank_sfz_stime' => $store_bank->bank_sfz_stime,
                    'bank_sfz_no' => $store_bank->bank_sfz_no,
                    'weixin_name' => $store->weixin_name,
                    'weixin_no' => $store->weixin_no,
                    'alipay_name' => $store->alipay_name,
                    'alipay_account' => $store->alipay_account,
                    'store_email' => $store->store_email,

                ];

                $data_r[$v] = $data;
            }

            if ($v == 'license_info') {
                $data = [
                    'store_license_no' => $store->store_license_no,
                    'store_license_time' => $store->store_license_time,
                    'store_license_stime' => $store->store_license_stime,
                    'store_license_img' => $store_img->store_license_img,
                    'store_other_img_a' => $store_img->store_other_img_a,
                    'store_other_img_b' => $store_img->store_other_img_b,
                    'store_other_img_c' => $store_img->store_other_img_c,
                    'store_industrylicense_img' => $store_img->store_industrylicense_img,
                    'head_sc_img' => $store_img->head_sc_img,
                    'head_store_img' => $store_img->head_store_img,
                ];

                $data_r[$v] = $data;
            }
        }

        return $this->successResponse("ok", $data_r);
    }

}